import { ifs } from '@/services';
import { N_cChartView } from './type';

class T_cmd {
  // 主组件箱
  private compBox: ifs.I_compBox;

  // 主组件ID
  private compID: string;

  // 主组件实例
  private self: any;
  // 主组refs

  // 主组件created里初始化
  public init(self: any, compBoxInfo: ifs.I_compBoxInfo) {
    this.self = self;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
  }
  public getTcmd(): T_cmd {
    return this;
  }

    // 格式化时间标签
  public formatTimeLabel(minutes: number): string {
    // 如果使用秒级显示，将分钟转换为秒
    if (this.self.useSecondsDisplay) {
      const seconds = Math.floor(minutes * 60);
      const hours = Math.floor(seconds / 3600);
      const mins = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;

      if (hours > 0) {
        return `${hours}:${mins
          .toString()
          .padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      }
      if (mins > 0) {
        return `${mins}:${secs.toString().padStart(2, '0')}`;
      }
      return `${secs}秒`;
    }

    if (this.self.timeRange === 'custom') {
      const actualDate = new Date(
        this.self.startDate.getTime() + minutes * 60 * 1000
      );
      const days = Math.floor(minutes / (24 * 60));
      const hours = Math.floor((minutes % (24 * 60)) / 60);
      const mins = Math.floor(minutes % 60);

      if (days > 0) {
        return `${days}天${hours}时`;
      }
      if (hours > 0) {
        return `${hours}:${mins.toString().padStart(2, '0')}`;
      }
      return `${mins}分`;
    }
    if (this.self.timeRange === 'week') {
      const days = Math.floor(minutes / (24 * 60));
      const hours = Math.floor((minutes % (24 * 60)) / 60);
      if (days > 0) {
        return `${days}天${hours}时`;
      }
      return `${hours}时`;
    }
    const hours = Math.floor(minutes / 60);
    const mins = Math.floor(minutes % 60);
    if (hours > 0) {
      return `${hours}:${mins.toString().padStart(2, '0')}`;
    }
    return `${mins}分`;
  }


    // 生成合适的刻度值，避免重复
  public generateNiceTicks(min: number, max: number, targetTicks?: number): number[] {
    const range = max - min;
    const ticks =
      targetTicks || (this.self.zoomLevel >= 2 ? 6 : this.self.zoomLevel >= 1 ? 5 : 4);

    // 计算合适的步长
    const step = range / (ticks - 1);

    // 将步长调整为"好看"的数字
    const magnitude = 10 ** Math.floor(Math.log10(step));
    const normalizedStep = step / magnitude;

    let niceStep: number;
    if (normalizedStep <= 1) {
      niceStep = 1 * magnitude;
    } else if (normalizedStep <= 2) {
      niceStep = 2 * magnitude;
    } else if (normalizedStep <= 5) {
      niceStep = 5 * magnitude;
    } else {
      niceStep = 10 * magnitude;
    }

    // 生成刻度值
    const result: number[] = [];
    const start = Math.ceil(min / niceStep) * niceStep;

    for (let value = start; value <= max + niceStep / 2; value += niceStep) {
      if (value >= min && value <= max) {
        result.push(value);
      }
    }

    // 确保包含最小值和最大值
    if (result.length === 0 || result[0] > min) {
      result.unshift(min);
    }
    if (result.length === 0 || result[result.length - 1] < max) {
      result.push(max);
    }

    return result.sort((a, b) => a - b);
  }


    // 获取时间范围
  getTimeRange(): { minX: number; maxX: number } {
    // 如果有实际数据，使用数据的时间范围
    if (this.self.sampleData.length > 0) {
      const times = this.self.sampleData.map(p => p.x);
      return {
        minX: Math.min(...times),
        maxX: Math.max(...times)
      };
    }

    // 如果没有数据，使用原来的逻辑
    if (this.self.timeRange === 'custom') {
      const timeDiff = this.self.endDate.getTime() - this.self.startDate.getTime();
      const minutesDiff = Math.floor(timeDiff / (1000 * 60));
      return { minX: 0, maxX: minutesDiff };
    }
    if (this.self.timeRange === 'week') {
      return { minX: 0, maxX: 7 * 24 * 60 }; // 7天，以分钟为单位
    }
    return { minX: 0, maxX: 24 * 60 }; // 1天，以分钟为单位
  }

    // 生成温度数据
  generateTemperatureData(): N_cChartView.Point[] {
    const data: N_cChartView.Point[] = [];
    const { maxX } = this.getTimeRange();

    // 根据时间范围确定数据点数量
    let dataPointCount: number;
    if (this.self.timeRange === 'custom') {
      dataPointCount = Math.max(100, Math.floor(maxX / 10)); // 每10分钟一个点
    } else if (this.self.timeRange === 'week') {
      dataPointCount = 168; // 一周168小时
    } else {
      dataPointCount = 144; // 一天144个点（每10分钟一个）
    }

    const interval = maxX / dataPointCount;

    // 基础温度，模拟更小的温度变化范围
    const baseTemp = 27.03;

    for (let i = 0; i < dataPointCount; i++) {
      const time = i * interval;

      // 使用多个正弦波叠加模拟复杂的温度变化
      const wave1 = Math.sin((i / dataPointCount) * Math.PI * 4) * 0.01;
      const wave2 = Math.sin((i / dataPointCount) * Math.PI * 12) * 0.005;
      const randomNoise = (Math.random() - 0.5) * 0.003;

      let temperature = baseTemp + wave1 + wave2 + randomNoise;

      // 随机添加一些异常值来测试功能
      if (Math.random() < 0.05) {
        // 5%的概率出现异常值
        if (Math.random() < 0.5) {
          temperature = 23 + Math.random() * 2; // 23-25度
        } else {
          temperature = 29 + Math.random() * 2; // 29-31度
        }
      }

      data.push({
        x: time, // 时间（分钟）
        y: temperature
      });
    }
    return data;
  }

}
interface I_cmd extends T_cmd { }
export { I_cmd, T_cmd };
